﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using Xtee.CodeDom.Wrapper;
using Xtee.Core;

namespace Xtee.CodeDom.MetaInfo
{
    public class ComplexTypeInfo:TypeInfo
    {
        private readonly XmlSchemaComplexType _xmlSchemaComplexType;
       
        private bool? _isUserDefined;
        public override bool IsUserDefined
        {
            get
            {
                if (_isUserDefined.HasValue)
                    return _isUserDefined.Value;

                if (_xmlSchemaComplexType.ContentModel is XmlSchemaSimpleContent)
                    return (_isUserDefined = IsComplexTypeUserDefined()).Value;
                
                if (_xmlSchemaComplexType.IsArray())
                    return (_isUserDefined = IsComplexTypeUserDefined()).Value;
                
                return (_isUserDefined = false).Value;
            }
        }

        public override bool IsAbstract => _xmlSchemaComplexType.IsAbstract;
        
        public ComplexTypeInfo(string fullName, XmlSchemaComplexType xmlSchemaComplexType, SchemaObjectClassInfo owner):base(fullName,xmlSchemaComplexType,owner)
        {
            _xmlSchemaComplexType = xmlSchemaComplexType;
        }
        

        private bool IsComplexTypeUserDefined()
        {
            if (_xmlSchemaComplexType.ContentModel?.Content is XmlSchemaSimpleContentExtension)
            {
                var simple = (XmlSchemaSimpleContentExtension)_xmlSchemaComplexType.ContentModel.Content;
                return simple.BaseTypeName.HasBuiltInType();
            }

            if (_xmlSchemaComplexType.ContentModel?.Content is XmlSchemaSimpleContentRestriction)
            {
                var simple = (XmlSchemaSimpleContentRestriction)(_xmlSchemaComplexType.ContentModel.Content);
                return simple.BaseTypeName.HasBuiltInType();
            }

            var wr = new XmlSchemaArrayItemTypeWrapper(_xmlSchemaComplexType, Resolver);

            XmlQualifiedName referencedTypeName = wr.GetArrayElement().SchemaTypeName;

            if (!referencedTypeName.IsEmpty) //refereeritud massivi element
            {
                if (wr.GetArrayElement().ElementSchemaType is XmlSchemaSimpleType)
                {
                    return !wr.GetArrayElement().ElementSchemaType.QualifiedName.HasBuiltInType();
                }
            }
            else if (wr.GetArrayElement().SchemaType is XmlSchemaSimpleType || wr.GetArrayElement().SchemaType is XmlSchemaComplexType)
            //anonyymne tyyp, mis asub elemendi sees , ehk siis userdefined ehk ,eraldi klass genereeritakse sell jaoks
            {
                return true;
            }

            return false;
        }
    }
}
